﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.MeetingReservations;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.MeetingReservations
{
    public class GetReservationDetailCommandHandler : IRequestHandler<GetReservationDetailCommand, APIResult<List<ReservationDto>>>
    {
        IBaseRepository<MeetingRoom> rRep;
        IMapper mapper;
        IBaseRepository<MeetingReservation> mtrRep;
        ILogger<GetReservationDetailCommandHandler> mlogger;

        public GetReservationDetailCommandHandler(IBaseRepository<MeetingReservation> mtrRep, ILogger<GetReservationDetailCommandHandler> mlogger, IMapper mapper, IBaseRepository<MeetingRoom> rRep)
        {
            this.mtrRep = mtrRep;
            this.mlogger = mlogger;
            this.mapper = mapper;
            this.rRep = rRep;
        }

        public async Task<APIResult<List<ReservationDto>>> Handle(GetReservationDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var reservation=await mtrRep.GetAll().FirstOrDefaultAsync(x=>x.MeetingReservationId==request.MeetingReservationId&&!x.IsDel);
                if (reservation == null) 
                { 
                    return new APIResult<List<ReservationDto>> 
                    {
                        Code=StatusEnumCode.Fail,
                        Message="未找到指定的会议预约信息",
                        Data=null
                    };
                }
                var singleReserDto=mapper.Map<ReservationDto>(reservation);
                var reserDto = new List<ReservationDto> { singleReserDto };
                List<MeetingRoom> rooms = rRep.GetAll().ToList();
                foreach (var item in reserDto)
                {
                    item.Location = rooms.Find(x => x.MeetingRoomId == item.MeetingRoomId).Location;
                }
                return new APIResult<List<ReservationDto>>
                {
                    Code=StatusEnumCode.Ok,
                    Message="获取会议预约详情成功",
                    Data=reserDto
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
